package com.mars.admin.modules.app;

import cn.dev33.satoken.stp.StpUtil;
import com.mars.admin.common.request.PublishPostRequest;
import com.mars.admin.common.util.PostUtil;
import com.mars.admin.framework.common.Result;
import com.mars.admin.modules.post.dto.PostWithUserDTO;
import com.mars.admin.modules.post.entity.Post;
import com.mars.admin.modules.post.service.IPostService;
import com.mars.admin.modules.post.vo.PostInfoVO;
import com.mybatisflex.core.paginate.Page;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 帖子控制器
 *
 * @author Mars
 * @version 1.0
 * @date 2025-01-07
 */
@Slf4j
@RestController
@RequestMapping("/api/post")
@Tag(name = "帖子管理", description = "帖子相关接口")
public class PostController {

    @Autowired
    private IPostService postService;

    /**
     * 分页查询帖子列表
     */
    @GetMapping("/page")
    @Operation(summary = "分页查询帖子列表", description = "分页查询帖子列表")
    public Result<Page<PostInfoVO>> page(
            @Parameter(description = "页码") @RequestParam(defaultValue = "1") Integer pageNumber,
            @Parameter(description = "每页数量") @RequestParam(defaultValue = "10") Integer pageSize,
            @Parameter(description = "用户ID") @RequestParam(required = false) Long userId,
            @Parameter(description = "话题ID") @RequestParam(required = false) Long topicId,
            @Parameter(description = "帖子类型") @RequestParam(required = false) Integer postType,
            @Parameter(description = "是否热门") @RequestParam(required = false) Integer isHot,
            @Parameter(description = "是否推荐") @RequestParam(required = false) Integer isRecommend,
            @Parameter(description = "状态") @RequestParam(required = false) Integer status,
            @Parameter(description = "审核状态") @RequestParam(required = false) Integer auditStatus,
            @Parameter(description = "搜索关键词") @RequestParam(required = false) String keyword) {
        try {
            Page<PostInfoVO> page = new Page<>(pageNumber, pageSize);

            Page<PostInfoVO> result = postService.getPostListWithUser(
                    page, userId, topicId, postType, isHot, isRecommend, status, auditStatus, keyword);

            return Result.success(result);
        } catch (Exception e) {
            log.error("分页查询帖子列表失败", e);
            return Result.error("查询失败：" + e.getMessage());
        }
    }

    /**
     * 根据ID查询帖子详情
     */
    @GetMapping("/{id}")
    @Operation(summary = "查询帖子详情", description = "根据ID查询帖子详情")
    public Result<PostInfoVO> getById(@Parameter(description = "帖子ID") @PathVariable Long id) {
        try {
            PostInfoVO postDetail = postService.getDetail(id);
            if (postDetail == null) {
                return Result.error("帖子不存在");
            }
            return Result.success(postDetail);
        } catch (Exception e) {
            log.error("查询帖子详情失败，帖子ID：{}", id, e);
            return Result.error("查询失败：" + e.getMessage());
        }
    }

    /**
     * 发布帖子
     */
    @PostMapping("/publish")
    @Operation(summary = "发布圈子帖子", description = "发布新帖子")
    public Result<Boolean> publish(@RequestBody PublishPostRequest request) {
        try {
            // 参数校验
            String validationError = PostUtil.validatePublishRequest(request);
            if (validationError != null) {
                return Result.error(validationError);
            }

            // 构建Post对象
            Post post = PostUtil.buildPostForPublish(request);

            // 检查是否有有效图片
            if (post.getImages() == null || post.getImages().isEmpty()) {
                return Result.error("没有有效的图片");
            }

            // 发布帖子
            boolean success = postService.publishPost(post, request.getTopicIds());
            if (success) {
                return Result.success("发布成功", true);
            } else {
                return Result.error("发布失败");
            }
        } catch (Exception e) {
            log.error("发布帖子失败，请求参数：{}", request, e);
            return Result.error("发布失败：" + e.getMessage());
        }
    }

    /**
     * 更新帖子
     */
    @PutMapping
    @Operation(summary = "更新帖子", description = "更新帖子信息")
    public Result<Boolean> update(@RequestBody PublishPostRequest request) {
        try {
            // 参数校验
            String validationError = PostUtil.validateUpdateRequest(request);
            if (validationError != null) {
                return Result.error(validationError);
            }

            // 构建Post对象
            Post post = PostUtil.buildPostForUpdate(request);

            // 检查是否有有效图片
            if (post.getImages() == null || post.getImages().isEmpty()) {
                return Result.error("没有有效的图片");
            }

            // 更新帖子
            boolean success = postService.updatePost(post, request.getTopicIds());
            if (success) {
                return Result.success("更新成功", true);
            } else {
                return Result.error("更新失败");
            }
        } catch (Exception e) {
            log.error("更新帖子失败，请求参数：{}", request, e);
            return Result.error("更新失败：" + e.getMessage());
        }
    }

    /**
     * 删除帖子
     */
    @DeleteMapping("/{id}")
    @Operation(summary = "删除帖子", description = "根据ID删除帖子")
    public Result<Boolean> delete(@Parameter(description = "帖子ID") @PathVariable Long id) {
        try {
            boolean success = postService.deletePost(id);
            if (success) {
                return Result.success("删除成功", true);
            } else {
                return Result.error("删除失败");
            }
        } catch (Exception e) {
            log.error("删除帖子失败，帖子ID：{}", id, e);
            return Result.error("删除失败：" + e.getMessage());
        }
    }

    /**
     * 查询热门帖子
     */
    @GetMapping("/hot")
    @Operation(summary = "查询热门帖子", description = "查询热门帖子列表")
    public Result<Page<Post>> getHotPosts(
            @Parameter(description = "页码") @RequestParam(defaultValue = "1") Integer pageNumber,
            @Parameter(description = "每页数量") @RequestParam(defaultValue = "10") Integer pageSize) {
        try {
            Page<Post> page = new Page<>(pageNumber, pageSize);
            Page<Post> result = postService.getHotPosts(page);
            return Result.success(result);
        } catch (Exception e) {
            log.error("查询热门帖子失败", e);
            return Result.error("查询失败：" + e.getMessage());
        }
    }

    /**
     * 查询推荐帖子
     */
    @GetMapping("/recommend")
    @Operation(summary = "查询推荐帖子", description = "查询推荐帖子列表")
    public Result<Page<Post>> getRecommendPosts(
            @Parameter(description = "页码") @RequestParam(defaultValue = "1") Integer pageNumber,
            @Parameter(description = "每页数量") @RequestParam(defaultValue = "10") Integer pageSize) {
        try {
            Page<Post> page = new Page<>(pageNumber, pageSize);
            Page<Post> result = postService.getRecommendPosts(page);
            return Result.success(result);
        } catch (Exception e) {
            log.error("查询推荐帖子失败", e);
            return Result.error("查询失败：" + e.getMessage());
        }
    }

    /**
     * 查询关注用户的帖子
     */
    @GetMapping("/following")
    @Operation(summary = "查询关注用户的帖子", description = "查询当前用户关注的用户发布的帖子")
    public Result<Page<Post>> getFollowingPosts(
            @Parameter(description = "用户ID") @RequestParam Long userId,
            @Parameter(description = "页码") @RequestParam(defaultValue = "1") Integer pageNumber,
            @Parameter(description = "每页数量") @RequestParam(defaultValue = "10") Integer pageSize) {
        try {
            Page<Post> page = new Page<>(pageNumber, pageSize);
            Page<Post> result = postService.getFollowingPosts(userId, page);
            return Result.success(result);
        } catch (Exception e) {
            log.error("查询关注用户的帖子失败，用户ID：{}", userId, e);
            return Result.error("查询失败：" + e.getMessage());
        }
    }

    /**
     * 搜索帖子
     */
    @GetMapping("/search")
    @Operation(summary = "搜索帖子", description = "根据关键词搜索帖子")
    public Result<Page<Post>> searchPosts(
            @Parameter(description = "搜索关键词") @RequestParam String keyword,
            @Parameter(description = "页码") @RequestParam(defaultValue = "1") Integer pageNumber,
            @Parameter(description = "每页数量") @RequestParam(defaultValue = "10") Integer pageSize) {
        try {
            if (keyword == null || keyword.trim().isEmpty()) {
                return Result.error("搜索关键词不能为空");
            }
            Page<Post> page = new Page<>(pageNumber, pageSize);
            Page<Post> result = postService.searchPosts(keyword.trim(), page);
            return Result.success(result);
        } catch (Exception e) {
            log.error("搜索帖子失败，关键词：{}", keyword, e);
            return Result.error("搜索失败：" + e.getMessage());
        }
    }

    /**
     * 点赞帖子
     */
    @PostMapping("/{id}/like")
    @Operation(summary = "点赞帖子", description = "对帖子进行点赞")
    public Result<Boolean> likePost(
            @Parameter(description = "帖子ID") @PathVariable Long id) {
        Long userId = StpUtil.getLoginIdAsLong();
        try {
            boolean success = postService.likePost(id, userId);
            if (success) {
                return Result.success("点赞成功", true);
            } else {
                return Result.error("点赞失败，可能已经点赞过了");
            }
        } catch (Exception e) {
            log.error("点赞帖子失败，帖子ID：{}，用户ID：{}", id, userId, e);
            return Result.error("点赞失败：" + e.getMessage());
        }
    }

    /**
     * 取消点赞帖子
     */
    @DeleteMapping("/{id}/like")
    @Operation(summary = "取消点赞帖子", description = "取消对帖子的点赞")
    public Result<Boolean> unlikePost(
            @Parameter(description = "帖子ID") @PathVariable Long id) {
        Long userId = StpUtil.getLoginIdAsLong();
        try {
            boolean success = postService.unlikePost(id, userId);
            if (success) {
                return Result.success("取消点赞成功", true);
            } else {
                return Result.error("取消点赞失败");
            }
        } catch (Exception e) {
            log.error("取消点赞帖子失败，帖子ID：{}，用户ID：{}", id, userId, e);
            return Result.error("取消点赞失败：" + e.getMessage());
        }
    }

    /**
     * 收藏帖子
     */
    @PostMapping("/{id}/collect")
    @Operation(summary = "收藏帖子", description = "收藏帖子到指定分组")
    public Result<Boolean> collectPost(
            @Parameter(description = "帖子ID") @PathVariable Long id,
            @Parameter(description = "用户ID") @RequestParam Long userId) {
        try {
            boolean success = postService.collectPost(id, userId);
            if (success) {
                return Result.success("收藏成功", true);
            } else {
                return Result.error("收藏失败，可能已经收藏过了");
            }
        } catch (Exception e) {
            log.error("收藏帖子失败，帖子ID：{}，用户ID：{}", id, userId, e);
            return Result.error("收藏失败：" + e.getMessage());
        }
    }

    /**
     * 取消收藏帖子
     */
    @DeleteMapping("/{id}/collect")
    @Operation(summary = "取消收藏帖子", description = "取消收藏帖子")
    public Result<Boolean> uncollectPost(
            @Parameter(description = "帖子ID") @PathVariable Long id,
            @Parameter(description = "用户ID") @RequestParam Long userId) {
        try {
            boolean success = postService.uncollectPost(id, userId);
            if (success) {
                return Result.success("取消收藏成功", true);
            } else {
                return Result.error("取消收藏失败");
            }
        } catch (Exception e) {
            log.error("取消收藏帖子失败，帖子ID：{}，用户ID：{}", id, userId, e);
            return Result.error("取消收藏失败：" + e.getMessage());
        }
    }

    /**
     * 审核帖子
     */
    @PutMapping("/{id}/audit")
    @Operation(summary = "审核帖子", description = "审核帖子状态")
    public Result<Boolean> auditPost(
            @Parameter(description = "帖子ID") @PathVariable Long id,
            @Parameter(description = "审核状态") @RequestParam Integer auditStatus,
            @Parameter(description = "审核原因") @RequestParam(required = false) String auditReason,
            @Parameter(description = "审核人ID") @RequestParam Long auditUserId) {
        try {
            boolean success = postService.auditPost(id, auditStatus, auditReason, auditUserId);
            if (success) {
                return Result.success("审核成功", true);
            } else {
                return Result.error("审核失败");
            }
        } catch (Exception e) {
            log.error("审核帖子失败，帖子ID：{}，审核状态：{}", id, auditStatus, e);
            return Result.error("审核失败：" + e.getMessage());
        }
    }

    /**
     * 设置帖子置顶状态
     */
    @PutMapping("/{id}/top")
    @Operation(summary = "设置帖子置顶状态", description = "设置帖子是否置顶")
    public Result<Boolean> setTop(
            @Parameter(description = "帖子ID") @PathVariable Long id,
            @Parameter(description = "是否置顶：0-否，1-是") @RequestParam Integer isTop) {
        try {
            boolean success = postService.setPostTop(id, isTop);
            if (success) {
                return Result.success("设置成功", true);
            } else {
                return Result.error("设置失败");
            }
        } catch (Exception e) {
            log.error("设置帖子置顶状态失败，帖子ID：{}，置顶状态：{}", id, isTop, e);
            return Result.error("设置失败：" + e.getMessage());
        }
    }

    /**
     * 设置帖子热门状态
     */
    @PutMapping("/{id}/hot")
    @Operation(summary = "设置帖子热门状态", description = "设置帖子是否热门")
    public Result<Boolean> setHot(
            @Parameter(description = "帖子ID") @PathVariable Long id,
            @Parameter(description = "是否热门：0-否，1-是") @RequestParam Integer isHot) {
        try {
            boolean success = postService.setPostHot(id, isHot);
            if (success) {
                return Result.success("设置成功", true);
            } else {
                return Result.error("设置失败");
            }
        } catch (Exception e) {
            log.error("设置帖子热门状态失败，帖子ID：{}，热门状态：{}", id, isHot, e);
            return Result.error("设置失败：" + e.getMessage());
        }
    }

    /**
     * 设置帖子推荐状态
     */
    @PutMapping("/{id}/recommend")
    @Operation(summary = "设置帖子推荐状态", description = "设置帖子是否推荐")
    public Result<Boolean> setRecommend(
            @Parameter(description = "帖子ID") @PathVariable Long id,
            @Parameter(description = "是否推荐：0-否，1-是") @RequestParam Integer isRecommend) {
        try {
            boolean success = postService.setPostRecommend(id, isRecommend);
            if (success) {
                return Result.success("设置成功", true);
            } else {
                return Result.error("设置失败");
            }
        } catch (Exception e) {
            log.error("设置帖子推荐状态失败，帖子ID：{}，推荐状态：{}", id, isRecommend, e);
            return Result.error("设置失败：" + e.getMessage());
        }
    }

    /**
     * 批量删除帖子
     */
    @DeleteMapping("/batch")
    @Operation(summary = "批量删除帖子", description = "根据ID列表批量删除帖子")
    public Result<Boolean> batchDelete(@RequestBody List<Long> ids) {
        try {
            if (ids == null || ids.isEmpty()) {
                return Result.error("帖子ID列表不能为空");
            }
            boolean success = postService.removeByIds(ids);
            if (success) {
                return Result.success("批量删除成功", true);
            } else {
                return Result.error("批量删除失败");
            }
        } catch (Exception e) {
            log.error("批量删除帖子失败，帖子ID列表：{}", ids, e);
            return Result.error("批量删除失败：" + e.getMessage());
        }
    }

    /**
     * 获取我的帖子列表
     */
    @GetMapping("/my")
    @Operation(summary = "获取我的帖子列表", description = "获取当前用户发布的帖子列表")
    public Result<Page<Post>> getMyPosts(
            @Parameter(description = "页码") @RequestParam(defaultValue = "1") Integer pageNumber,
            @Parameter(description = "每页数量") @RequestParam(defaultValue = "10") Integer pageSize,
            @Parameter(description = "状态筛选") @RequestParam(required = false) Integer status) {
        try {
            Page<Post> page = new Page<>(pageNumber, pageSize);
            long userId = StpUtil.getLoginIdAsLong();
            Page<Post> result = postService.getPostsByUserId(userId, page);
            return Result.success(result);
        } catch (Exception e) {
            return Result.error("查询失败：" + e.getMessage());
        }
    }

}